package cn.lili.modules.audit.service.impl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.audit.entity.dos.AuditPartner;
import cn.lili.modules.audit.entity.dto.AuditDto;
import cn.lili.modules.audit.entity.dto.AuditPartnerDto;
import cn.lili.modules.audit.entity.dto.LowListDto;
import cn.lili.modules.audit.entity.vo.AuditPartnerVo;
import cn.lili.modules.audit.enums.AuditPartnerStatus;
import cn.lili.modules.audit.mapper.AuditPartnerMapper;
import cn.lili.modules.audit.service.AuditPartnerService;
import cn.lili.modules.goods.entity.dos.Brand;
import cn.lili.modules.goods.entity.dto.BrandPageDTO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.RechargeFowService;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.mybatis.util.PageUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.rowset.serial.SerialException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Date;

@Slf4j
@Service
public class AuditPartnerServiceImpl extends ServiceImpl<AuditPartnerMapper, AuditPartner>
		implements
			AuditPartnerService {
	@Autowired
	private PartnerMapper partnerMapper;

	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private EextensionService eextensionService;
	@Autowired
	private MemberWalletService memberWalletService;
	@Autowired
	private RechargeFowService rechargeFowService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private TransferService transferService;

	@Autowired
	private RegionService regionService;

	@Override
	public IPage<AuditPartnerVo> getByPage(AuditPartnerDto partnerDto) {
		log.info("注销审核人列表，入参:{}", JSON.toJSONString(partnerDto));
		QueryWrapper<AuditPartner> queryWrapper = new QueryWrapper<>();
		// 传0代表查询已审核的数据
		if ("0".equals(partnerDto.getAuditStatus())) {
			queryWrapper.in("a.audit_status", AuditPartnerStatus.PASS.getCode(), AuditPartnerStatus.REFUSE.getCode());
		}
		// 传1代表查询待审核的数据
		if ("1".equals(partnerDto.getAuditStatus())) {
			queryWrapper.in("a.audit_status", AuditPartnerStatus.AUDITING.getCode());
		}
		if (StringUtils.isNotEmpty(partnerDto.getStartTime())) {
			queryWrapper.ge("a.create_time", partnerDto.getStartTime());
		}
		if (StringUtils.isNotEmpty(partnerDto.getEndTime())) {
			queryWrapper.le("a.create_time", partnerDto.getEndTime());
		}
		if (StringUtils.isNotEmpty(partnerDto.getMobile())) {
			queryWrapper.eq("e.mobile", partnerDto.getMobile());
		}
		if (StringUtils.isNotEmpty(partnerDto.getAddress())) {
			queryWrapper.like("f.region_id", partnerDto.getAddress() + "%");
		}
		queryWrapper.isNotNull("e.id");
		queryWrapper.orderByDesc("a.create_time");
		IPage<AuditPartnerVo> byPage = this.baseMapper.getByPage(PageUtil.initPage(partnerDto), queryWrapper);
		if (CollectionUtils.isNotEmpty(byPage.getRecords())) {
			// 根据ad_code查询区域
			byPage.getRecords().forEach(item -> {
				item.setRegion(regionService.getItemAdCodOrName(item.getRegion()));
				if (StringUtils.isNotEmpty(item.getRechargeMoney())) {
					item.setRechargeMoney(
							new BigDecimal(item.getRechargeMoney()).setScale(2, RoundingMode.DOWN).toString());
				}
				if (StringUtils.isNotEmpty(item.getRecharge())) {
					item.setRecharge(new BigDecimal(item.getRecharge()).setScale(2, RoundingMode.DOWN).toString());
				}
				if (StringUtils.isNotEmpty(item.getPromote())) {
					item.setPromote(new BigDecimal(item.getPromote()).setScale(2, RoundingMode.DOWN).toString());
				}
				// 下辖会员数
				QueryWrapper<Member> query = new QueryWrapper<>();
				query.eq("m.id", item.getMemberId());
				query.orderByAsc("c.LEVEL");
				query.last("limit 1");
				MemberVO member = memberMapper.findByUsername(query);
				QueryWrapper<AuditPartner> wrapper = new QueryWrapper<>();
				wrapper.eq("a.id", member.getId());
				wrapper.eq("a.delete_flag", 0);
				wrapper.eq("aa.delete_flag", 0);
				if (member.getPartnerType() != null && member.getPartnerType() == 1) {// 事业
					wrapper.eq("aa.have_store", 1);
				} else if (member.getPartnerType() != null && member.getPartnerType() == 2) {// 天使
					wrapper.eq("aa.have_store", 0);
				}
				wrapper.eq("c.delete_flag", 0);
				wrapper.isNotNull("a.promotion_code");
				List<LowListDto> lowList = this.baseMapper.getLowList(wrapper);
				int memberNum = 0;
				if (CollectionUtils.isNotEmpty(lowList)) {
					memberNum = lowList.size();
				}
				item.setMemberNum(memberNum);
			});
		}
		return byPage;
	}

	@Override
	public Boolean audit(AuditDto auditDto) {
		try {
			AuditPartner auditPartner = this.baseMapper.selectById(auditDto.getAuditId());
			if (auditPartner == null) {
				throw new ServiceException(ResultCode.ERROR);
			}
			if (AuditPartnerStatus.LIST.contains(AuditPartnerStatus.getStatus(auditDto.getAuditStatus()))) {
				auditPartner.setAuditStatus(auditDto.getAuditStatus());
				auditPartner.setAuditMsg(auditDto.getAuditMsg());
				auditPartner.setAuditDate(new Date());
				this.baseMapper.updateById(auditPartner);
			}
			String memberId = auditPartner.getMemberId();
			// 通过
			if (AuditPartnerStatus.PASS.getCode() == auditDto.getAuditStatus()) {
				Partner partner = partnerMapper.findPartnerByMemberId(memberId);
				if (partner == null) {
					log.error("撤销合伙人-未检测到合伙人数据 入参memberId：{}", memberId);
					return Boolean.FALSE;
				}
				Boolean status = partnerMapper.updateByMemberId(memberId);
				if (status) {

					Member member = memberMapper.selectById(memberId);
					if (member == null) {
						log.error("撤销合伙人-未检测到会员数据 入参memberId：{}", memberId);
						return Boolean.FALSE;
					}
					// 解绑下级会员,释放下级会员可绑定关系;
					eextensionService.updateByExtensionCode(member.getPromotionCode());
				}
			}

		} catch (Exception e) {
			log.error("撤销合伙人异常：{}", e);
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

	@Override
	public Boolean getBackMsg(AuditDto auditDto) {
		AuditPartner auditPartner = this.baseMapper.selectById(auditDto.getAuditId());
		if (auditPartner == null) {
			throw new ServiceException(ResultCode.ERROR);
		}
		auditPartner.setBackAmount(auditDto.getBackAmount());
		auditPartner.setBackUser(auditDto.getBackUser());
		auditPartner.setBackMobile(auditDto.getBackMobile());
		this.baseMapper.updateById(auditPartner);
		// 平台退回端口费
		if (auditDto.getBackAmount().compareTo(BigDecimal.ZERO) > 0) {
			QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("m.mobile", auditDto.getBackMobile());
			queryWrapper.orderByAsc("c.LEVEL");
			queryWrapper.last("limit 1");
			MemberVO memberVO = memberService.findByPhone(queryWrapper);
			// 添加订单
			Transfer transfer = new Transfer();
			transfer.setPayee("admin");
			transfer.setPayeeName("平台");
			transfer.setTransferMoney(auditDto.getBackAmount().doubleValue());
			transfer.setPaymentWallet(WalletOwnerEnum.RECHARGE.name());
			transfer.setPayer(memberVO.getId());
			transfer.setType("PORT_FEE");
			String sn = SnowFlake.createStr("Z");
			transfer.setSn(sn);
			Member payer = memberService.getById(transfer.getPayer());// 收款人
			MemberWallet from = memberWalletService.getMemberWalletInfo(payer.getId(), WalletOwnerEnum.RECHARGE.name());
			MemberWallet to = memberWalletService.getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台");

			memberWalletService.transferPay(sn, from, to, auditDto.getBackAmount().doubleValue(), 0D, "PORT_FEE");
			transfer.setPaymentTime(new Date());
			transfer.setState("success");
			transferService.save(transfer);
		}
		return Boolean.TRUE;
	}

	@Override
	public IPage<LowListDto> getLowList(String memberId) {
		AuditDto auditDto = new AuditDto();
		auditDto.setMemberId(memberId);
		QueryWrapper<Member> query = new QueryWrapper<>();
		query.eq("m.id", memberId);
		query.orderByAsc("c.LEVEL");
		query.last("limit 1");
		MemberVO member = memberMapper.findByUsername(query);
		QueryWrapper<AuditPartner> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("a.id", memberId);
		queryWrapper.eq("a.delete_flag", 0);
		queryWrapper.eq("aa.delete_flag", 0);
		if ("1".equals(member.getPartnerType())) {// 事业
			queryWrapper.eq("aa.have_store", 1);
		} else if ("2".equals(member.getPartnerType())) {// 天使
			queryWrapper.eq("aa.have_store", 0);
		}
		queryWrapper.eq("c.delete_flag", 0);
		queryWrapper.isNotNull("a.promotion_code");
		IPage<LowListDto> lowList = this.baseMapper.getLowListPage(PageUtil.initPage(auditDto), queryWrapper);
		if (CollectionUtils.isNotEmpty(lowList.getRecords())) {
			// 根据ad_code查询区域
			lowList.getRecords().forEach(item -> {
				item.setRegion(regionService.getItemAdCodOrName(item.getRegion()));
			});
		}
		return lowList;
	}
}
